package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;
    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        System.out.println("XMLMapperBuilder.parse----->"+inputStream.toString());
        Document read = new SAXReader().read(inputStream);
        Element rootElement = read.getRootElement();

        String namesapce = rootElement.attributeValue("namespace");
        System.out.println("namespace--------->"+namesapce);
        List<Element> list = rootElement.selectNodes("//select");
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String paramType = element.attributeValue("paramType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParamType(paramType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            String key = namesapce + "." + id;
            System.out.println("statementid------->"+ key);
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }

}
